﻿#region 命名空间

using System;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;

using WinnerCMS.Common;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 移除缓存
    /// </summary>
    [ConfigurationElementType(typeof (CustomCallHandlerData))]
    public class CacheRemoveHandler : ICallHandler
    {
        /// <summary>
        /// 构造函数，此构造函数是用于Attribute调用
        /// </summary>
        /// <param name="key">缓存id</param>
        public CacheRemoveHandler(string key)
        {
            Key = key;
        }

        /// <summary>
        /// 构造函数，此处不可省略，否则会导致异常
        /// </summary>
        /// <param name="attributes">配置文件中所配置的参数</param>
        public CacheRemoveHandler(NameValueCollection attributes)
        {
            Key = String.IsNullOrEmpty(attributes["Key"]) ? "" : attributes["Key"];
            Order = Convert.ToInt32(attributes["Order"]);
        }

        /// <summary>
        /// 实现ICallHandler.Invoke方法，用于对具体拦截方法做相应的处理
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //检查参数是否存在
            if (input == null) throw new ArgumentNullException("input");
            if (getNext == null) throw new ArgumentNullException("getNext");

            if (Key.Contains("@p") && input.Inputs.Count > 0 && input.Arguments.Count > 0)
            {
                TextTemplate temp = new TextTemplate
                {
                    Inputs = input.Inputs
                };
                temp.Convert(Key);

                temp.Params.ForEach(x => { Key = Key.Replace(x.Key, x.Value); });
            }
            //调用具体方法
            var result = getNext()(input, getNext);

            if (!Key.IsNullOrEmpty())
                CacheHelper.Remove(Key);

            return result;
        }

        /// <summary>
        /// 缓存id
        /// </summary>
        public string Key { get; set; }

        /// <summary>
        /// 执行顺序
        /// </summary>
        public int Order { get; set; }
    }
}